
#include "lthread.h"
#ifndef WINCE
	#include <process.h>
#endif // WINCE

LThread::LThread( void )
:handle_(NULL)
,userData_(NULL)
,isRunning_(false)
,threadID_(0)
{
}

LThread::~LThread( void )
{
	if (handle_ != NULL)
	{
		CloseHandle(handle_);
		handle_ = NULL;
	}
}

bool LThread::start(void* data, bool suspended)
{
	if(NULL!=handle_) return false;
	this->userData_ = data;

#ifndef WINCE
	handle_ = (HANDLE)_beginthreadex(NULL,0,_threadProc,this,
		(suspended)?CREATE_SUSPENDED:0,&threadID_);
#else
	handle_ = CreateThread(NULL, 0, _threadProc,this, (suspended)?CREATE_SUSPENDED:0, &threadID_);
#endif

	isRunning_ = (handle_!=0) ? true : false;
	return isRunning_;
}

bool LThread::terminate(int ret)
{
	if(!handle_)
		return false;
	isRunning_ = !TerminateThread(handle_,ret);
	if(isRunning_==false)
	{
		CloseHandle(handle_);
		handle_ = NULL;
	}
	return !isRunning_;
}

int LThread::suspend()
{
	int ret = SuspendThread(handle_);
	isRunning_ = (ret<=0);
	return ret;
}

int LThread::resume()
{
	int ret = ResumeThread(handle_);
	isRunning_ = (ret<=0);
	return ret;
}

#ifndef WINCE
unsigned int LThread::_threadProc(void* param)
{
	LThread* pThread = (LThread*)param;
	int ret = pThread->threadProc();
	return ret;
}
#else
unsigned long LThread::_threadProc(void* param)
{
	LThread* pThread = (LThread*)param;
	int ret = pThread->threadProc();
	return ret;
}
#endif



unsigned int LThread::threadProc()
{
	isRunning_ = false;
#ifdef WINCE
#else
	_endthreadex(0);
#endif
	return 0;
}

unsigned long LThread::waitThreadUntilOver( DWORD milliseconds )
{
	return WaitForSingleObject(handle_,milliseconds);
}

bool LThread::isRunning() const
{
	return isRunning_;
}

void* LThread::getData()
{ 
	return userData_;
}

BOOL LThread::setPriority( Priority priority )
{ 
	return SetThreadPriority(handle_,priority); 
}

LThread::Priority LThread::getPriority()
{ 
	return static_cast<Priority>(GetThreadPriority(handle_)); 
}

HANDLE LThread::getThreadHandle()
{ 
	return handle_; 
}

unsigned int LThread::getThreadID() const
{
	return threadID_; 
}